﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySerialization;

namespace CrudApp
{
    public partial class CrudMainForm : Form
    {
        public CrudMainForm()
        {
            InitializeComponent();
            showData();
        }

        pList plist;

        void showData()
        {
            plist = new pList();
            infoDataGrid.Rows.Clear();
            plist.Read();

            foreach (Person p in plist)
            {
                infoDataGrid.Rows.Add(p.id, p.FName, p.LName, p.Age);
            }
        }

        private void AddButton_Click(object sender, EventArgs e)
        {
            EditForm editForm = new EditForm();
            editForm.ShowDialog(this);
            if (editForm.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                plist = new pList();
                plist.Add(new Person
                {
                    id = editForm.idFromEditForm,
                    FName = editForm.fnameFromEditForm,
                    LName = editForm.lnameFromEditForm,
                    Age = editForm.ageFromEditForm
                });
                plist.Create(plist[0]as Person);
            }
            showData();
        }

        private void EditButton_Click(object sender, EventArgs e)
        {
            EditForm editForm = new EditForm();
            editForm.ShowDialog(this);
            if (editForm.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                plist = new pList();
                plist.Update(editForm.idFromEditForm,
                    editForm.fnameFromEditForm,
                    editForm.lnameFromEditForm,
                    editForm.ageFromEditForm);
            }
            showData();
        }

        private void DeleteButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure?", "Delete record", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.OK)
            {
                plist.Delete(Convert.ToInt32(IdToDelTextBox.Text));
            }
            showData();
        }
    }
}
